package ext.vpde.cadvaulting.migration;

import java.io.*;
import java.util.*;

import ext.vpde.cadvaulting.util.WINDSQL;

import wt.epm.EPMApplicationType;
import wt.epm.EPMAuthoringAppType;
import wt.epm.EPMAuthoringAppVersion;
import wt.epm.EPMDocument;
import wt.fc.*;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.folder.Foldered;
import wt.query.*;
import wt.vc.VersionControlHelper;
import wt.vc.Versioned;
import wt.inf.container.*;
import wt.method.RemoteMethodServer;
import wt.pdmlink.PDMLinkProduct;
import wt.adapter.BasicWebjectDelegate;
import wt.inf.library.WTLibrary;
import wt.epm.familytable.*;

public class LoadUtil {
	
	public static PrintWriter openOutputFile(String fileName) throws Exception {
		File f = new File(fileName);
        FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
        PrintWriter outFile  = new PrintWriter((OutputStream)fos,true);
        return outFile;
	}
	
	public static void printProgress(int lineNumber) {
		if (lineNumber%100 == 0) 
			System.out.println(lineNumber + " " + Calendar.getInstance().getTime());
	}
	
	public static void printException(String methodName, Exception e) {
		System.out.println("***** ERROR IN METHOD: " + methodName + ": " + e.getLocalizedMessage());
	}

	public static Hashtable processInputLine(String s) {
		Hashtable ht  = new Hashtable();
		String docStr = "";
    	String subStr = "";
    	String folderName = "/Default";
    	
		StringTokenizer strTok = new StringTokenizer(s,"|");
		ht.put("CADNAME",strTok.nextToken());
		String docTypeStr = strTok.nextToken();
		ht.put("VERSION",strTok.nextToken());
		ht.put("ITERATION",strTok.nextToken());
		String state = strTok.nextToken();
		ht.put("DOCNAME",strTok.nextToken());
		ht.put("FILEPATH",strTok.nextToken());
		ht.put("CONTAINERTYPE",strTok.nextToken());
		String contName = strTok.nextToken();
		ht.put("SOURCE",strTok.nextToken());
		ht.put("SOURCEID",strTok.nextToken());
		ht.put("CREATOR",strTok.nextToken());
		ht.put("CREATED",strTok.nextToken());
		ht.put("MODIFIER",strTok.nextToken());
		ht.put("MODIFIED",strTok.nextToken());
		ht.put("FTSTATUS",strTok.nextToken());
    	
    	if (docTypeStr.indexOf("/") > 0 ) {
    		docStr = docTypeStr.substring(0,docTypeStr.indexOf("/"));
    		subStr = docTypeStr.substring(docTypeStr.indexOf("/")+1);
    	} else {
    		docStr = docTypeStr;
    	}
    	
    	if (contName.indexOf("/") > 0) {
			folderName += contName.substring(contName.indexOf("/"));
			contName    = contName.substring(0,contName.indexOf("/"));
		}
    	
    	ht.put("FOLDERNAME", folderName);
    	ht.put("CONTAINERNAME",contName);
    	ht.put("DOCTYPE",docStr);
    	ht.put("SUBTYPE",subStr);
    	ht.put("STATE",getStateValue(state));
    	
		return ht;
	}
	
    public static WTContainer getContainer(String containerType, String containerName) {
    	WTContainer container = null;
    	QuerySpec qs = null;
    	QueryResult qr = null;
    	try {
    		if (containerType.equals("product")) {
    			qs = new QuerySpec(PDMLinkProduct.class);
    			qs.appendWhere(new SearchCondition(PDMLinkProduct.class,"containerInfo.name","=",containerName));
    			qr = PersistenceHelper.manager.find(qs);
    			if (qr.size() > 0) container = (PDMLinkProduct)qr.nextElement();
    			else System.out.println("CONTAINER: " + containerName + " NOT FOUND");
    		} else {
    			qs = new QuerySpec(WTLibrary.class);
    			qs.appendWhere(new SearchCondition(WTLibrary.class,"containerInfo.name","=",containerName));
    			qr = PersistenceHelper.manager.find(qs);
    			if (qr.size() > 0) container = (WTLibrary)qr.nextElement();
    			else System.out.println("CONTAINER: " + containerName + " NOT FOUND");
    		}
    	} catch(Exception e) { printException("LoadUtil.getContainer", e); }
		return container;
    }
    
	public static String getStateValue(String state) {
		     if (state.equals("Released"))    state = "RELEASED";
		else if (state.equals("In Approval")) state = "UNDERREVIEW";
		else state = "INWORK";
		return state;
	}
	
	public static EPMAuthoringAppVersion getAuthoringAppVersion() {
		EPMAuthoringAppVersion epmaav = null;
		try {
			QuerySpec qs = new QuerySpec(wt.epm.EPMAuthoringAppVersion.class);
			qs.appendWhere(new SearchCondition(wt.epm.EPMAuthoringAppVersion.class,"authoringApplication","=","PROE"));
			qs.appendOrderBy(wt.epm.EPMAuthoringAppVersion.class, "thePersistInfo.createStamp", true);
			QueryResult qr = PersistenceHelper.manager.find(qs);
			epmaav = (EPMAuthoringAppVersion)qr.nextElement();
		} catch (Exception e) { printException("LoadUtil.getAuthoringAppVersion", e); }
		return epmaav;
	}
	
	/*
    public static void setFolder( WTContainerRef containerRef, FolderEntry the_folder_entry, String CADName ) throws WTException {
    	Folder folder;
    	String  folderName = "/Default/Other";
    	
	     	  if (CADName.endsWith(".prt")) folderName = "/Default/Parts";
	     else if (CADName.endsWith(".asm")) folderName = "/Default/Assemblies";
	     else if (CADName.endsWith(".drw")) folderName = "/Default/Drawings";
	     else if (CADName.endsWith(".frm")) folderName = "/Default/Formats";
	     else if (CADName.endsWith(".lay")) folderName = "/Default/Layouts";
	     else if (CADName.endsWith(".mfg")) folderName = "/Default/Manufacturing";
	     	
	    try {
	    	folder = FolderHelper.service.getFolder(folderName, containerRef);
	    }
	    catch(FolderNotFoundException e) {
	    	folder = FolderHelper.service.createSubFolder( folderName, containerRef );
	    }
	    FolderHelper.assignLocation(the_folder_entry, folder);
    }
    */
    
	public static EPMDocument getEPMDocument(String CADName) {
		EPMDocument doc = null;
		try {
			String  obid = "OR:wt.epm.EPMDocument:" + WINDSQL.getLatestRevision(CADName);
			doc = (EPMDocument)BasicWebjectDelegate.getObjectByUfid(obid);
		} catch (Exception e) { LoadUtil.printException("LoadUtil.getDocument", e);	}
		return doc;
	}
	
	public static String getIdFromPersistable(Persistable p) {
		String ida2a2 = p.getPersistInfo().getObjectIdentifier().getStringValue();
        ida2a2 = ida2a2.substring(ida2a2.lastIndexOf(":")+1);
        return ida2a2;
	}

	public static boolean loginRemote(String userid, String userpw) {
		boolean loginOK = false;
		try {
			RemoteMethodServer.getDefault().setUserName(userid);
			RemoteMethodServer.getDefault().setPassword(userpw);
			loginOK = true;
		} catch(Exception e) {
			printException("LoadUtil.loginRemote", e); 
		}
		return loginOK;
	}
	
	public static BufferedReader openInputFile(String theFile) {
		BufferedReader file = null;
		try {
			file = new BufferedReader(new FileReader(theFile));
		} catch (Exception e) { 
			printException("LoadUtil.openInputFile", e); 
		}
		return file;
	}
	
	public static EPMDocument newEPMDocument(String ida2a2) {
		EPMDocument doc = null;
		try {
			doc = (EPMDocument)BasicWebjectDelegate.getObjectByUfid("OR:wt.epm.EPMDocument:"+ida2a2);
		} catch (Exception e) { LoadUtil.printException("newEPMDocument", e); }
		return doc;
	}
	
	public static String createFamilyTable(String genIda2a2, String fName) {
		String ida2a2 = null;
		try {
			EPMDocument generic = (EPMDocument)BasicWebjectDelegate.getObjectByUfid("OR:wt.epm.EPMDocument:" + genIda2a2);
			WTContainerRef wtcr = generic.getContainerReference();
			
			if (generic != null) {
				try {
				Folder folder = FolderHelper.service.getFolder((Foldered)generic);
			
				EPMSepFamilyTableMaster esftm = new EPMSepFamilyTableMaster();
			
				esftm.setName(generic.getCADName());
				esftm.setSeries("wt.series.HarvardSeries");
				esftm.setOwnerApplication(EPMApplicationType.toEPMApplicationType("EPM"));
				esftm.setAuthoringApplication(EPMAuthoringAppType.toEPMAuthoringAppType("PROE"));
				esftm.setContainerReference(wtcr);
				
				EPMFamilyTableMaster eftm = (EPMFamilyTableMaster)PersistenceHelper.manager.save(((Persistable) (esftm)));
			
				EPMSepFamilyTable esft = EPMSepFamilyTable.newEPMSepFamilyTable(eftm,folder);
				
				// set the version
	    		//MultilevelSeries mls = MultilevelSeries.newMultilevelSeries("wt.series.HarvardSeries.FileBased",fVer);
	    		//esft.setVersionInfo(VersionInfo.newVersionInfo(mls));

				Persistable p = PersistenceHelper.manager.save(esft);
				ida2a2 = LoadUtil.getIdFromPersistable(p);
				
				} catch(Exception e) { System.out.println("UNABLE TO CREATE FAMILY TABLE: " + e.getLocalizedMessage()); }
			
			}
		} catch (Exception e) {	LoadUtil.printException("LoadFamilyTable.createFamilyTable", e); }
		return ida2a2;
	}
	
	public static String reviseFamilyTable(String familyTableName, String version) throws Exception {
		String ida2a2 = null;
		try {
			String ftObid = WINDSQL.getObidFromFamilyTableName(familyTableName);
			EPMSepFamilyTable esft = (EPMSepFamilyTable)BasicWebjectDelegate.getObjectByUfid(ftObid);
			System.out.println("FOUND FAMILY TABLE TO REVISE: " + esft.getName()+" "+esft.getVersionIdentifier().getValue());
			Versioned newVer = VersionControlHelper.service.newVersion(esft);

			Persistable p = PersistenceHelper.manager.save(newVer);
			ida2a2 = p.getPersistInfo().getObjectIdentifier().getStringValue();
			ida2a2 = ida2a2.substring(ida2a2.lastIndexOf(":")+1);
		} catch (Exception e) {	
			LoadUtil.printException("UNABLE TO REVISE FAMLY TABLE: " + familyTableName + ", " + version, e);
			e.printStackTrace();
		}
		return ida2a2;
	}
	
	public static String createUserXML(String user) {
		String xmlStr = " <csvUser handler=\"wt.load.LoadUser.createUser\">\n";
		xmlStr += "  <csvuser></csvuser>\n";
		xmlStr += "  <csvnewUser>" + user + "</csvnewUser>\n";
		xmlStr += "  <csvwebServerID>" + user + "</csvwebServerID>\n";
		xmlStr += "  <csvfullName>" + user + "</csvfullName>\n";
		xmlStr += "  <csvLocale></csvLocale>\n";
		xmlStr += "  <csvEmail>" + user + "@whirlpool.com</csvEmail>\n";
		xmlStr += "  <csvDescription></csvDescription>\n";
		xmlStr += "  <csvTitle></csvTitle>\n";
		xmlStr += "  <csvOrganization>Whirlpool</csvOrganization>\n";
		xmlStr += "  <csvStreet1></csvStreet1>\n";
		xmlStr += "  <csvStreet2></csvStreet2>\n";
		xmlStr += "  <csvCity></csvCity>\n";
		xmlStr += "  <csvState></csvState>\n";
		xmlStr += "  <csvCountry></csvCountry>\n";
		xmlStr += "  <csvZipCode></csvZipCode>\n";
		xmlStr += "  <csvignore>x</csvignore>\n";
		xmlStr += "  <csvpassword>whr</csvpassword>\n";
		xmlStr += " </csvUser>";
		return xmlStr;
	}
	
	public static String createUserGroupXML( String group, String  user) {
		String  xmlStr = " <csvUserGroup handler=\"wt.load.LoadUser.createUserGroup\">\n";
		xmlStr += "  <csvuser></csvuser>\n";
		xmlStr += "  <csvgroupName>" + group + "</csvgroupName>\n";
		xmlStr += "  <csvuserName>" + user + "</csvuserName>\n";
		xmlStr += " </csvUserGroup>\n";
		return xmlStr;
	}
	
	public static String createGroupXML( String group) {
		String  xmlStr = " <csvGroup handler=\"wt.load.LoadUser.createGroup\">\n";
		xmlStr += "  <csvuser></csvuser>\n";
		xmlStr += "  <csvgroupName>" + group + "</csvgroupName>\n";
		xmlStr += "  <csvdescription></csvdescription>\n";
		xmlStr += "  <csvDirectoryService/>\n";
		xmlStr += " </csvGroup>\n";
		return xmlStr;
	}
	
	public static void writeXMLHeader(PrintWriter pw) {
		pw.println("<?xml version=\"1.0\" ?><!DOCTYPE NmLoader SYSTEM \"standardX10.dtd\">");
		pw.println("<NmLoader>");
	}
	
	public static void writeXMLFooter(PrintWriter pw) {
		pw.println("</NmLoader>");
	}
}
